﻿using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ZRT.RHPX.Entity;

namespace ZRT.RHPX.Core.Ioc
{
    /// <summary>
    /// 使用Ninject实现依赖注入
    /// </summary>
    public class NinjectDependencyResolver : IDependencyResolver
    {
        static object syncObj = new object();
        static Dictionary<string, IKernel> KernelDic = new Dictionary<string, IKernel>();
        public IKernel CurrentKernel { get; private set; }

        public NinjectDependencyResolver(string KernelName = "")
        {
            if (KernelDic.ContainsKey(KernelName))
            {
                this.CurrentKernel = KernelDic[KernelName];
                return;
            }
            lock (syncObj)
            {
                if (KernelDic.ContainsKey(KernelName))
                {
                    this.CurrentKernel = KernelDic[KernelName];
                    return;
                }

                IKernel Kernel = new StandardKernel();
                //Kernel.Bind<IUserRepository>().To<UserRepository>();
                KernelDic.Add(KernelName, Kernel);
                this.CurrentKernel = KernelDic[KernelName];
            }
        }

        public object GetService(Type serviceType)
        {
            return this.CurrentKernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return this.CurrentKernel.GetAll(serviceType);
        }
    }
}
